import { Pool } from 'pg'

// PostgreSQL连接配置
const pool = new Pool({
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT || '5432'),
  database: process.env.DB_NAME || 'aide',
  user: process.env.DB_USER || 'postgres',
  password: process.env.DB_PASSWORD || 'unidt@123',
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
})

export async function migrateDatabase(): Promise<void> {
  const client = await pool.connect()
  
  try {
    console.log('🔄 开始数据库迁移...')
    
    // 检查user_id字段是否存在
    const columnCheck = await client.query(`
      SELECT column_name 
      FROM information_schema.columns 
      WHERE table_name = 'tasks' AND column_name = 'user_id'
    `)
    
    if (columnCheck.rows.length === 0) {
      console.log('📝 添加user_id字段到tasks表...')
      
      // 添加user_id字段
      await client.query(`
        ALTER TABLE tasks 
        ADD COLUMN user_id TEXT
      `)
      
      // 为现有数据设置默认值
      await client.query(`
        UPDATE tasks 
        SET user_id = 'default_user' 
        WHERE user_id IS NULL
      `)
      
      console.log('✅ user_id字段添加成功')
    } else {
      console.log('ℹ️ user_id字段已存在，跳过迁移')
    }
    
    console.log('🎉 数据库迁移完成')
  } catch (error) {
    console.error('❌ 数据库迁移失败:', error)
    throw error
  } finally {
    client.release()
  }
}

// 如果直接运行此文件，执行迁移
if (require.main === module) {
  migrateDatabase()
    .then(() => {
      console.log('迁移完成')
      process.exit(0)
    })
    .catch((error) => {
      console.error('迁移失败:', error)
      process.exit(1)
    })
}
